<template>
  <div class="dispatch">
    <el-row
      :align="'middle'"
      :gutter="10"
    >
      <el-col :span="12">
        <div class="search-bar">
          <el-input
            v-model="keyword"
            placeholder="可输入师傅名称快速查询"
          >
          </el-input>
        </div>
      </el-col>
      <el-col :span="6">
        <el-date-picker
          v-model="dateValue"
          type="date"
          placeholder="选择日期"
        />
      </el-col>
      <el-col :span="6">
        <div class="tags">
          <div class="tag dispatched">
            <div class="box"></div>
            <span class="text">已派单</span>
          </div>
          <div class="tag undelivered">
            <div class="box"></div>
            <span class="text">未派单</span>
          </div>
        </div>
      </el-col>
    </el-row>
    <div class="content">
      <ul class="order-list">
        <li
          v-for="(item, index) in filterTaskList"
          :key="item.name"
          class="order-item"
          :class="(item.tasks && item.tasks.length > 0) ? 'dispatched' : 'undelivered'"
          @click="handleClickItem(item, index)"
          >
          <div class="user">
            <div class="avatar">
              <img v-if="item.gender == 1" src="@/assets/img/woker_man.png" alt="">
              <img v-else src="@/assets/img/woker_women.png" alt="">
            </div>
            <div class="name">{{ item.name }}</div>
          </div>
          <div v-if="(item.tasks && item.tasks.length > 0)" class="task-status">
            <span>已派 <span class="task-count">{{ item.tasks[0].timeIds.length }}</span> 单</span>
            <span class="link">点击查看</span>
          </div>
          <div v-else class="time">
            <span>未派单</span>
            <span class="link">点击派单</span>
          </div>
        </li>
        <li class="placeholder-li"></li>
        <li class="placeholder-li"></li>
        <li class="placeholder-li"></li>
        <li class="placeholder-li"></li>
        <li class="placeholder-li"></li>
        <li class="placeholder-li"></li>
      </ul>
      <el-empty v-show="!taskList || taskList.length === 0" description="暂无数据" />
    </div>
    <el-dialog v-model="dialogTaskVisible" title="派单管理" width="500" @close="handleCancelAction">
      <template #header>
        <div class="dialog-header">
          <div class="title">
            派单管理
          </div>
          <div class="user">
            <div class="avatar">
              <img v-if="currentWoker.gender == 1" src="@/assets/img/woker_man.png" alt="">
              <img v-else src="@/assets/img/woker_women.png" alt="">
            </div>
            <div class="info">
              <div class="item">姓名:<span class="value">{{ currentWoker.name }}</span></div>
              <div class="item">年龄:<span class="value">{{ currentWoker.age }}</span></div>
              <div class="item">工作经验:<span class="value">{{ currentWoker.workingAge }}</span></div>
              <div class="item">技能:<span class="value">{{ currentWoker.skill }}</span></div>
              <div class="item">手机号码:<span class="value">{{ currentWoker.mobilePhone }}</span></div>
            </div>
          </div>
          <div class="subtitle">
            请选择已派单的时间
          </div>
        </div>
      </template>
      <el-checkbox-group v-model="checkList">
        <el-checkbox v-for="item in defaultTimeArr" :key="item.id" :value="item.id" :label="`${item.start} ~ ${item.end}`" />
      </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelAction">取消</el-button>
          <el-button type="primary" @click="handleConfirmAction()">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue'
import useTaskStore from '@/store/task/task'
import { format } from 'date-fns'

const keyword = ref('')
const toDay = new Date()
const dateValue = ref(toDay)
const taskStore = useTaskStore()
const taskList = ref([])
const dialogTaskVisible = ref(false)
const checkList = ref([])
const defaultWoker = {
  name: '',
  gender: '',
  age: '',
  workingAge: '',
  skill: '',
  mobilePhone: ''
}
const currentWoker = ref(defaultWoker)
const defaultTimeArr = [
  {
    id: '1',
    start: '08:00',
    end: '10:00'
  },
  {
    id: '2',
    start: '10:00',
    end: '12:00'
  },
  {
    id: '3',
    start: '12:00',
    end: '14:00'
  },
  {
    id: '4',
    start: '14:00',
    end: '16:00'
  },
  {
    id: '5',
    start: '16:00',
    end: '18:00'
  },
  {
    id: '6',
    start: '18:00',
    end: '20:00'
  }
]

// 监听日期变化
watch(dateValue, (newValue) => {
  loadTaskList()
})

const filterTaskList = computed(() =>
  taskList.value.filter(
    (data) =>
      !keyword.value ||
      data.name.toLowerCase().includes(keyword.value.toLowerCase())
  )
)

function loadTaskList() {
  const dateString = format(dateValue.value, 'yyyy-MM-dd')
  taskStore.getTasks(50, 0, dateString).then((res) => {
    if (res.code === 0) {
      if (res.data && res.data.length > 0) {
        taskList.value = res.data.map(item => {
          if (item.tasks && item.tasks.length > 0) {
            return {
              ...item,
              tasks: item.tasks.map(task => {
                return {
                  ...task,
                  timeIds: task.timeIndexs.split(',')
                }
              })
            }
          } else {
            return item
          }
        })
      } else {
        taskList.value = []
      }
      console.log('获取任务列表成功: ', taskList.value)
    } else {
      taskList.value = []
      console.log('获取任务列表失败: ', res.message)
      ElMessage({
        message: res.message,
        type: 'error'
      })
    }
  }).catch((err) => {
    if (err) {
      console.log('err: ', err)
      ElMessage({
        message: '获取任务列表失败 ~',
        type: 'error'
      })
    }
  })
}

const handleClickItem = (item, index) => {
  console.log('item: ', item)
  currentWoker.value = item
  if (item.tasks && item.tasks.length > 0 && item.tasks[0].timeIds && item.tasks[0].timeIds.length > 0) {
    checkList.value = item.tasks[0].timeIds
  } else {
    checkList.value = []
  }
  dialogTaskVisible.value = true
}

const handleCancelAction = () => {
  dialogTaskVisible.value = false
}

const handleConfirmAction = () => {
  const checkValue = checkList.value.join(',')
  let oldCheckValue = ''
  if (currentWoker.value.tasks && currentWoker.value.tasks.length > 0) {
    oldCheckValue = currentWoker.value.tasks[0].timeIndexs
  } else {
    oldCheckValue = ''
  }

  if (checkValue === oldCheckValue) {
    ElMessage({
      message: '没有改变派单时间',
      type: 'warning'
    })
    return
  }

  const date = format(dateValue.value, 'yyyy-MM-dd')
  let taskId = '-1'
  if (currentWoker.value.tasks && currentWoker.value.tasks.length > 0) {
    taskId = currentWoker.value.tasks[0].id
  }
  // id为-1或'-1'时，会创建新的任务
  taskStore.updateTask({
    id: taskId,
    staffId: currentWoker.value.id,
    timeIndexs: checkValue,
    date: format(dateValue.value, 'yyyy-MM-dd')
  }).then(res => {
    if (res.code === 0) {
      loadTaskList()
      dialogTaskVisible.value = false
    } else {
      ElMessage({
        message: res.message,
        type: 'error'
      })
    }
  }).catch(err => {
    if (err) {
      ElMessage({
        message: '派单失败 ~',
        type: 'error'
      })
    }
  })
}

onMounted(() => {
  loadTaskList()
})

</script>

<style lang="scss" scoped>
.dispatch {
  padding: 10px;
  .tags {
    display: flex;
    justify-content: flex-end;
    .tag {
      display: flex;
      align-items: center;
      .box {
        width: 30px;
        height: 10px;
      }
      .text {
        margin-left: 10px;
        font-size: 12px;
        color: #666;
      }
    }
    .dispatched {
      .box {
        background-color: #b3e19d;
      }
    }
    .undelivered {
      margin-left: 20px;
      .box {
        background-color: #dedede;
      }
    }
  }

  .content {
    padding: 40px 0;
    .order-list {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      .order-item {
        width: 160px;
        min-height: 90px;
        padding: 10px;
        margin-bottom: 15px;
        border-radius: 5px;
        color: #333;
        font-size: 14px;
        box-sizing: border-box;
        cursor: pointer;
        .user {
          display: flex;
          align-items: center;
          .avatar {
            img {
              width: 40px;
              height: 40px;
              border-radius: 50%;
            }
          }
          .name {
            margin-left: 10px;
          }
        }
        .time {
          margin-top: 10px;
          font-size: 12px;
          .link {
            margin-left: 20px;
            color: #31a4ff;
          }
        }
        .task-status {
          margin-top: 10px;
          font-size: 12px;
          .task-count {
            font-size: 14px;
            color: var(--el-color-danger);
          }
          .link {
            margin-left: 20px;
            color: #409eff;
          }
        }
      }
      .dispatched {
        // background-color: #42c3af;
        background-color: #b3e19d;
      }
      .undelivered {
        background-color: #dedede;
        &:hover {
          background-color: #ffc15e;
        }
      }
      .placeholder-li {
        width: 160px;
        height: 0;
      }
    }
  }

  .dialog-header {
    .title {
      text-align: center;
      font-size: 18px;
      padding: 10px 0 20px;
      border-bottom: 1px solid var(--el-color-primary);
    }
    .subtitle {
      padding: 20px 0 0;
      font-size: 14px;
      color: #666;
    }
    .user {
      padding: 20px 0;
      display: flex;
      align-items: center;
      border-bottom: 1px solid var(--el-color-primary);
      .avatar {
        img {
          width: 60px;
          height: 60px;
          border-radius: 50%;
        }
      }
      .info {
        margin-left: 10px;
        padding: 0 10px;
        font-size: 14px;
        color: #666;
        .item {
          padding: 4px 0;
          .value {
            margin-left: 10px;
            color: #333;
            font-size: 14px;
          }
        }
      }
    }
  }
}
</style>